package com.seselin.joke.http;

import java.io.IOException;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Seselin on 2016/7/21.
 */
public class HttpUtil {



    public static String request(String url, Map<String, Object> param) {
        if ((param != null) && !param.isEmpty()) {
            for (String key : param.keySet()) {
                if (url.contains("?")) {
                    url += ("&" + (key + "=" + param.get(key)));
                } else {
                    url += ("?" + key + "=" + param.get(key));
                }
            }
        }

        Request request = new Request.Builder()
                .url(url)
                .header("User-Agent", "OkHttp Headers.java")
                .addHeader("Accept", "application/json; q=0.5")
                .addHeader("Accept", "application/vnd.github.v3+json")
                .build();

        try {
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful())
                throw new IOException("Unexpected code " + response);
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
